package com.itdong.securityconfig.controller;

import com.itdong.domain.User;
import com.itdong.securityconfig.dao.LoginUser;
import com.itdong.securityconfig.service.LoginService;
import com.itdong.vc.ResultVc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public ResultVc login(@RequestBody User user){
        log.info(user.toString());
        ResultVc resultVc = loginService.userLogin(user);
        return resultVc;
    }

    @GetMapping("/loginOut")
    public ResultVc loginOut(){
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long id = principal.getUser().getId();
        Boolean delete = redisTemplate.delete("login:" + id);
        if (delete){
            return new ResultVc(true, "您已退出登录");
        }else{
            return new ResultVc(false, "退出登录失败");
        }
    }
}
